package com.yami.shop.im.socket;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.Json;
import com.yami.shop.im.bean.ImMsgBizUserHistory;
import com.yami.shop.im.bo.SysSessionInfo;
import com.yami.shop.im.bo.UserSessionInfo;
import com.yami.shop.im.constants.MsgCode;
import com.yami.shop.im.hanlder.SecurityHandler;
import com.yami.shop.im.param.MessageInfo;
import com.yami.shop.im.service.ImMsgBizUserHistoryService;
import com.yami.shop.im.vo.MsgItem;
import com.yami.shop.security.multishop.model.YamiShopUser;
import com.yami.shop.security.platform.model.YamiSysUser;
import com.yami.shop.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 平台收到的消息
 * 10,"无法获取用户信息"
 * 11,"账户已在别处登录，请刷新"
 * 12,"对方不在线"
 * 13, "内容格式有误"
 *
 * @author Lzk
 */
@ServerEndpoint("/im/websocket/platform/{token}")
@Component
@Slf4j
public class SysWebSocketServer {

    /**
     * userId为key
     */
    public static final ConcurrentHashMap<String, SysSessionInfo> SYS_MAP = new ConcurrentHashMap<>(256);

    private static final String USER_PREFIX = "USER_";

    private static final String SYS_PREFIX = "SYS_";

    private static SecurityHandler securityHandler;

    private static UserService userService;

    private static ImMsgBizUserHistoryService imMsgBizUserHistoryService;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        securityHandler = applicationContext.getBean(SecurityHandler.class);
        userService = applicationContext.getBean(UserService.class);
        imMsgBizUserHistoryService = applicationContext.getBean(ImMsgBizUserHistoryService.class);
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        log.info("创建连接");
        YamiSysUser sysUser = securityHandler.getSysUser(token);
        if (sysUser == null) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(10, "无法获取用户信息")));
            return;
        }

        // 如果原来就有token
        SysSessionInfo oldSysSessionInfo = SYS_MAP.get(SYS_PREFIX + sysUser.getUserId());
        if (oldSysSessionInfo != null) {
            // 客户端收到11，关闭ws链接，弹出提示
            if (oldSysSessionInfo.getSession().isOpen()) {
                oldSysSessionInfo.getSession().getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(11, "账户已在别处登录，请刷新")));
                oldSysSessionInfo.getSession().close();
            }
        }

        SysSessionInfo sysSessionInfo = new SysSessionInfo();
        sysSessionInfo.setNickName(sysUser.getNickName());
        sysSessionInfo.setUserId(sysUser.getUserId());
        sysSessionInfo.setSession(session);

        SYS_MAP.put(SYS_PREFIX + sysSessionInfo.getUserId(), sysSessionInfo);
        session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success()));
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("token") String token) {
        log.info("关闭连接");
        YamiSysUser yamiSysUser = securityHandler.getSysUser(token);
        if (yamiSysUser == null) {
            return;
        }
        SYS_MAP.remove(SYS_PREFIX + yamiSysUser.getUserId());
    }

    /**
     * 连接错误调用的方法
     */
    @OnError
    public void onError(Session session, @PathParam("token") String token, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
        YamiSysUser yamiSysUser = securityHandler.getSysUser(token);
        if (yamiSysUser == null) {
            return;
        }
        SYS_MAP.remove(SYS_PREFIX + yamiSysUser.getUserId());
    }

    /**
     * 收到客户端消息后调用的方法，该消息由用户发过来
     *
     * @param sourceMessage 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String sourceMessage, @PathParam("token") String token, Session session) throws IOException {
        // from user info
        YamiSysUser sysUser = securityHandler.getSysUser(token);
        if (Objects.isNull(sysUser)) {
            log.error("无法获取用户信息");
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(10, "无法获取用户信息")));
            return;
        }

        if (StrUtil.isBlank(sourceMessage)) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(13, "内容格式有误")));
            return;
        }

        log.info("sourceMessage: " + sourceMessage);

        MessageInfo messageInfo = Json.parseObject(sourceMessage, MessageInfo.class);

        if (Objects.isNull(messageInfo)) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(13, "内容格式有误")));
            return;
        }

        // 保持心跳
        if (StrUtil.equals(messageInfo.getContent(), Constant.HEART_BEAT)) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(0, "保持心跳")));
            return;
        }

        String userId = messageInfo.getToId();
        User user = userService.getUserByUserId(userId);
        if (Objects.isNull(user)) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(14, "参数有误")));
            return;
        }

        sendToUser(messageInfo, sysUser, user, session, userId);
    }

    public void sendToUser(MessageInfo messageInfo, YamiSysUser sysUser, User user, Session session, String userId) throws IOException {
        // 获取消息历史
        if (Objects.nonNull(messageInfo.getHistory()) && Objects.equals(messageInfo.getHistory(), true)) {
            Page<MsgItem> msgItemPage = imMsgBizUserHistoryService.getPlatformUserHistory(sysUser, messageInfo, user);
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.HISTORY, msgItemPage)));
            return;
        }

        // 标记消息已读
        if (Objects.nonNull(messageInfo.getRead()) && Objects.equals(messageInfo.getRead(), true)) {
            if (Objects.nonNull(messageInfo.getMsgIds()) && !messageInfo.getMsgIds().isEmpty()) {
                List<ImMsgBizUserHistory> imMsgBizUserHistories = imMsgBizUserHistoryService.markPlatformUserRead(messageInfo, sysUser, userId);
                if (!imMsgBizUserHistories.isEmpty()) {
                    session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success()));
                    UserSessionInfo userSessionInfo = UserWebSocketServer.USER_MAP.get(USER_PREFIX + messageInfo.getToId());
                    if (Objects.nonNull(userSessionInfo)) {
                        userSessionInfo.getSession().getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.READ, messageInfo.getMsgIds())));
                    }
                }
            }
            return;
        }

        // 发送消息
        if (Objects.nonNull(messageInfo.getContent()) && !messageInfo.getContent().isEmpty()) {
            ImMsgBizUserHistory imMsgBizUserHistory = imMsgBizUserHistoryService.savePlatformUserHistory(messageInfo, sysUser);
            // 在线的话发送消息，不在线的话留言
            UserSessionInfo userSessionInfo = UserWebSocketServer.USER_MAP.get(USER_PREFIX + messageInfo.getToId());
            if (Objects.nonNull(userSessionInfo)) {
                SysSessionInfo sysSessionInfo = SYS_MAP.get(SYS_PREFIX + sysUser.getUserId());
                MsgItem msgItem = imMsgBizUserHistoryService.getUserPlatformMsgItem(sysSessionInfo, userSessionInfo, imMsgBizUserHistory);
                userSessionInfo.getSession().getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(msgItem)));
            }
        }
    }

}
